import Taro from '@tarojs/taro';
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, ScrollView } from '@tarojs/components';
import { MaterialIcons } from 'taro-icons';
import './index.scss';

// 消息类型定义
interface Message {
  id: number;
  type: 'system' | 'student';
  title: string;
  content: string;
  sender?: string;
  avatar?: string;
  createTime: string;
  isRead: boolean;
  relatedId?: number;
  relatedType?: 'student' | 'appointment' | 'payment';
}

const MessageCenterPage: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'all' | 'system' | 'student'>('all');
  const [unreadCount, setUnreadCount] = useState(0);

  useEffect(() => {
    // 设置页面标题
    Taro.setNavigationBarTitle({ title: '消息中心' });
    // 加载消息数据
    loadMessageData();
  }, []);

  const loadMessageData = async () => {
    try {
      setIsLoading(true);
      // 模拟API调用
      // const response = await getMessagesApi();
      
      // 模拟数据
      const mockMessages: Message[] = [
        {
          id: 1,
          type: 'system',
          title: '系统通知：平台更新公告',
          content: '驾招无忧平台将于2024年2月1日进行系统升级，届时可能会有短暂的服务中断，请提前做好准备。',
          createTime: '2024-01-20 10:00:00',
          isRead: false
        },
        {
          id: 2,
          type: 'student',
          title: '学员约课提醒',
          content: '您的学员张三预约了明天上午10:00-12:00的练车课程，请及时确认。',
          sender: '张三',
          avatar: 'https://via.placeholder.com/40x40',
          createTime: '2024-01-19 16:30:00',
          isRead: false,
          relatedId: 101,
          relatedType: 'student'
        },
        {
          id: 3,
          type: 'system',
          title: '教练评分更新',
          content: '您的教学评分已更新为4.9分，排名上升至本站第5名，继续加油！',
          createTime: '2024-01-18 09:00:00',
          isRead: true
        },
        {
          id: 4,
          type: 'student',
          title: '学员消息',
          content: '教练您好，我想请问一下科目二考试需要注意哪些事项？',
          sender: '李四',
          avatar: 'https://via.placeholder.com/40x40',
          createTime: '2024-01-17 20:15:00',
          isRead: true,
          relatedId: 102,
          relatedType: 'student'
        },
        {
          id: 5,
          type: 'system',
          title: '支付成功通知',
          content: '学员王五已成功支付C1手动挡课程费用，您将获得相应的教学提成。',
          createTime: '2024-01-16 14:45:00',
          isRead: true,
          relatedId: 201,
          relatedType: 'payment'
        }
      ];
      
      setMessages(mockMessages);
      
      // 计算未读消息数量
      const count = mockMessages.filter(msg => !msg.isRead).length;
      setUnreadCount(count);
    } catch (error) {
      console.error('加载消息失败:', error);
      Taro.showToast({
        title: '数据加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleMessagePress = async (message: Message) => {
    // 标记为已读
    if (!message.isRead) {
      setMessages(prevMessages => 
        prevMessages.map(msg => 
          msg.id === message.id ? { ...msg, isRead: true } : msg
        )
      );
      setUnreadCount(prevCount => prevCount - 1);
      
      // 模拟API调用标记已读
      // await markMessageAsReadApi(message.id);
    }
    
    // 根据消息类型和相关内容进行跳转
    if (message.relatedId && message.relatedType) {
      switch (message.relatedType) {
        case 'student':
          Taro.navigateTo({
            url: `/pages/student-detail/index?id=${message.relatedId}`
          });
          break;
        case 'appointment':
          // 假设存在预约详情页面
          // Taro.navigateTo({
          //   url: `/pages/appointment-detail/index?id=${message.relatedId}`
          // });
          break;
        case 'payment':
          // 假设存在支付详情页面
          // Taro.navigateTo({
          //   url: `/pages/payment-detail/index?id=${message.relatedId}`
          // });
          break;
      }
    }
  };

  const handleMarkAllAsRead = async () => {
    try {
      Taro.showLoading({ title: '处理中...' });
      
      // 更新本地数据
      setMessages(prevMessages => 
        prevMessages.map(msg => ({ ...msg, isRead: true }))
      );
      setUnreadCount(0);
      
      // 模拟API调用
      // await markAllMessagesAsReadApi();
      
      Taro.hideLoading();
      Taro.showToast({
        title: '已全部标记为已读',
        icon: 'success'
      });
    } catch (error) {
      console.error('标记已读失败:', error);
      Taro.hideLoading();
      Taro.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
  };

  const getTypeIcon = (type: string) => {
    return type === 'system' ? 'notifications' : 'person';
  };

  const getTypeColor = (type: string) => {
    return type === 'system' ? '#1890ff' : '#52c41a';
  };

  const getTypeText = (type: string) => {
    return type === 'system' ? '系统通知' : '学员消息';
  };

  const getTimeAgo = (timeStr: string) => {
    const now = new Date();
    const messageTime = new Date(timeStr);
    const diffMs = now.getTime() - messageTime.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);
    
    if (diffMins < 60) {
      return `${diffMins}分钟前`;
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return messageTime.toLocaleDateString('zh-CN');
    }
  };

  const filteredMessages = messages.filter(message => {
    if (activeTab === 'all') return true;
    return message.type === activeTab;
  }).sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime());

  return (
    <View className="message-center-page">
      {/* 顶部操作栏 */}
      {unreadCount > 0 && (
        <TouchableOpacity className="mark-all-read"
          onPress={handleMarkAllAsRead}
        >
          <MaterialIcons name="check-all" size={16} color="#1890ff" />
          <Text className="mark-all-read-text">全部标记为已读</Text>
        </TouchableOpacity>
      )}

      {/* 标签栏 */}
      <View className="tab-bar">
        <TouchableOpacity 
          className={`tab ${activeTab === 'all' ? 'active' : ''}`}
          onPress={() => setActiveTab('all')}
        >
          <Text className="tab-text">全部消息</Text>
          {unreadCount > 0 && (
            <View className="badge">
              <Text className="badge-text">{unreadCount}</Text>
            </View>
          )}
        </TouchableOpacity>
        <TouchableOpacity 
          className={`tab ${activeTab === 'system' ? 'active' : ''}`}
          onPress={() => setActiveTab('system')}
        >
          <Text className="tab-text">系统通知</Text>
          {messages.filter(msg => msg.type === 'system' && !msg.isRead).length > 0 && (
            <View className="badge">
              <Text className="badge-text">
                {messages.filter(msg => msg.type === 'system' && !msg.isRead).length}
              </Text>
            </View>
          )}
        </TouchableOpacity>
        <TouchableOpacity 
          className={`tab ${activeTab === 'student' ? 'active' : ''}`}
          onPress={() => setActiveTab('student')}
        >
          <Text className="tab-text">学员消息</Text>
          {messages.filter(msg => msg.type === 'student' && !msg.isRead).length > 0 && (
            <View className="badge">
              <Text className="badge-text">
                {messages.filter(msg => msg.type === 'student' && !msg.isRead).length}
              </Text>
            </View>
          )}
        </TouchableOpacity>
      </View>

      {/* 消息列表 */}
      {isLoading ? (
        <View className="loading-container">
          <Text>加载中...</Text>
        </View>
      ) : (
        <ScrollView className="message-scroll">
          {filteredMessages.length > 0 ? (
            filteredMessages.map(message => (
              <TouchableOpacity 
                key={message.id} 
                className={`message-item ${!message.isRead ? 'unread' : ''}`}
                onPress={() => handleMessagePress(message)}
              >
                <View className="message-left">
                  <View className="message-icon"
                    style={{ backgroundColor: getTypeColor(message.type) }}
                  >
                    <MaterialIcons name={getTypeIcon(message.type)} size={24} color="#fff" />
                  </View>
                  {!message.isRead && (
                    <View className="unread-dot"></View>
                  )}
                </View>
                <View className="message-content">
                  <View className="message-header">
                    <Text className="message-title">{message.title}</Text>
                    <Text className="message-time">{getTimeAgo(message.createTime)}</Text>
                  </View>
                  <Text className="message-text">{message.content}</Text>
                  {message.type === 'student' && message.sender && (
                    <View className="message-sender">
                      <Text className="sender-text">发送者：{message.sender}</Text>
                    </View>
                  )}
                </View>
                <MaterialIcons name="chevron-right" size={24} color="#ccc" className="message-arrow" />
              </TouchableOpacity>
            ))
          ) : (
            <View className="empty-container">
              <MaterialIcons name="mail-outline" size={80} color="#ccc" />
              <Text className="empty-text">暂无消息</Text>
            </View>
          )}
        </ScrollView>
      )}
    </View>
  );
};

export default MessageCenterPage;